package cn.lsnu.utils;

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class UploadTool {


    public static String uploadImg(String pathName, HttpServletRequest request) throws Exception{
//        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//        MultipartHttpServletRequest mRequest = resolver.resolveMultipart(request);
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        String path = request.getSession().getServletContext().getRealPath(pathName);
        //图片上传成功后，将图片的地址写到数据库
        File fileUrl=new File(path);
        //如果当前项目里不存在images文件夹，就创建
        if(!fileUrl.exists()){
            fileUrl.mkdir();
        }
        String filePaths= "";
        Map<String, MultipartFile> fileMap = mRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> mpfile : fileMap.entrySet()) {
            MultipartFile mf = mpfile.getValue();
            // 获得原始文件名
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
            String res = sdf.format(new Date());
            //获取图片的原始图片的后缀名
            String ext = FilenameUtils.getExtension(mf.getOriginalFilename());
            ext = ext.substring(0,ext.indexOf("?"));
            File targetFile = new File(path,"/"+res+"."+ext);
            mf.transferTo(targetFile);
            filePaths =filePaths + pathName+res+"."+ext+"-";
        }
        return filePaths;
    }
}
